package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    final RoleMapper roleMapper;
    final RoleResourceMapper roleResourceMapper;

    /**
     * 角色分页条件查询
     *
     * @param pageNum
     * @param pageSize
     * @param dto
     * @return
     */
    @Override
    @Cacheable(cacheNames = "role", key = "#pageNum + #pageSize + #dto.hashCode()")
    public PageBean<RoleVo> pageQuery(Integer pageNum, Integer pageSize, RoleDto dto) {
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        //分页查询
        Page<Role> page = roleMapper.selectPage(dto);
        return PageBean.of(page, RoleVo.class);
    }

    /**
     * 添加角色
     *
     * @param dto
     */
    @Override
    @CacheEvict(cacheNames = "role", allEntries = true)
    public void addRole(RoleDto dto) {
        Role role = BeanUtil.toBean(dto, Role.class);
        roleMapper.insert(role);
    }

    /**
     * 修改角色（启用禁用、编辑、角色授权）
     *
     * @param dto
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = "role", allEntries = true)
    public void updateRole(RoleDto dto) {
        //完成 启用禁用、编辑 这两个功能
        Role role = BeanUtil.toBean(dto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);

        //完成  角色授权  这个功能   （判断）
        String[] checkedResourceNos = dto.getCheckedResourceNos();
        if (ArrayUtil.isEmpty(checkedResourceNos)) {
            //结束业务
            return;
        }

        //操作中间表，根据角色id删除数据
        roleResourceMapper.deleteByRoleId(dto.getId());

        //操作中间表，添加角色-资源关系（多条  遍历checkedResourceNos）
        for (String resourceNo : checkedResourceNos) {
            //构建pojo对象
            RoleResource roleResource = RoleResource.builder()
                    .roleId(dto.getId())
                    .resourceNo(resourceNo)
                    .dataState("0") //0正常 1停用
                    .build();
            //添加角色资源关系
            roleResourceMapper.insert(roleResource);
        }

    }

    /**
     * 根据角色查询对应的资源编号
     *
     * @param roleId
     * @return
     */
    @Override
    @Cacheable(cacheNames = "role", key = "#roleId")
    public Set<String> findCheckedResource(Long roleId) {
        return roleResourceMapper.selectResourceNoByRoleId(roleId);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = "role", allEntries = true)
    public void deleteById(Long id) {
        //1. 判断角色的状态
        Role role = roleMapper.selectByPrimaryKey(id);
        if (StrUtil.equals(role.getDataState(), "0")) { //0启用  1停用
            throw new RuntimeException("不能删除已启用的角色");
        }

        //2. 根据id删除角色
        roleMapper.deleteByPrimaryKey(id);

        //3. 根据角色id删除对应的资源
        roleResourceMapper.deleteByRoleId(id);
    }

    /**
     * 查询所有角色、角色下拉框
     */
    @Override
    @Cacheable(cacheNames = "role", key = "#root.methodName")
    public List<RoleVo> list() {
        List<Role> roleList = roleMapper.list();
        return BeanUtil.copyToList(roleList, RoleVo.class);
    }

}
